package com.seemygo.shop.cloud.mq.listener;

import com.seemygo.shop.cloud.exception.BusinessException;
import com.seemygo.shop.cloud.mq.MQLogSendCallback;
import com.seemygo.shop.cloud.mq.msg.*;
import com.seemygo.shop.cloud.resp.CodeMsg;
import com.seemygo.shop.cloud.service.IOrderInfoService;
import com.seemygo.shop.cloud.util.JSONUtil;
import com.seemygo.shop.cloud.web.SeckillCodeMsg;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RocketMQMessageListener(
        topic = MQConstants.SECKILL_ORDER_TOPIC,
        selectorExpression = MQConstants.CREATE_ORDER_TAG,
        consumerGroup = MQConstants.CREATE_ORDER_CONSUMER_GROUP )
public class CreateOrderMQListener implements RocketMQListener<CreateSeckillOrderMsg> {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(CreateSeckillOrderMsg createSeckillOrderMsg) {
        log.info("[创建订单消费者]收到创建订单消息" , JSONUtil.toJSONString(createSeckillOrderMsg));
        try {
            String orderNo = orderInfoService.doSeckill(createSeckillOrderMsg.getSeckillId(), createSeckillOrderMsg.getUserId());
            try {
                //创建订单成功
                //发送创建订单成功的消息，由websocket通知客户端
                rocketMQTemplate.asyncSend(MQConstants.SECKILL_SUCCESS_DEST, new SeckillSuccessMsg(createSeckillOrderMsg.getUuid(), orderNo), new MQLogSendCallback());
                rocketMQTemplate.asyncSend(MQConstants.DELAY_ORDE_DEST, new GenericMessage<>(new DelayOrderMsg(orderNo, createSeckillOrderMsg.getSeckillId())),
                        new MQLogSendCallback(), 1000, 3);
            }catch (Exception e){
                log.error("[创建订单消费者] 发送创建订单获延迟消息失败！", e);
            }
        } catch (Exception e){
            log.error("[创建订单消费者] 创建订单失败！", e);
            CodeMsg codeMsg = SeckillCodeMsg.OP_ERROR;
            if(e instanceof BusinessException){
                BusinessException be = (BusinessException) e;
                codeMsg = be.getCodeMsg();
            }
            rocketMQTemplate.asyncSend(MQConstants.SECKILL_FAILED_DEST,new SeckillFailedMsg(createSeckillOrderMsg.getUuid(), codeMsg), new MQLogSendCallback());
            orderInfoService.seckillFailed(createSeckillOrderMsg.getSeckillId(), createSeckillOrderMsg.getUserId());

        }

    }
}
